#!/usr/bin/python
import time
import os

from Adafruit_CharLCD import Adafruit_CharLCD
from subprocess import * 
from time import sleep, strftime
from datetime import datetime

class Display():

    def __init__(self):
        self.runfile = 'run.file'
        f = open(self.runfile,'w')
        f.write('keep running')

    def checkRunFile(self):
        bOK = False
        try:
            f = open(str(self.runfile),'r')
            bOK = True 
        except:
            pass
        return bOK 
        
    def run_cmd(self,cmd):
        p = Popen(cmd, shell=True, stdout=PIPE)
        output = p.communicate()[0]
        return output
		
    def run(self):
        start_index = 0
        prev_content = ''
        cmd = "mpc current"
        lcd = Adafruit_CharLCD()
        lcd.clear()
        lcd.backlightOn()
        lcd.begin(16,2)
        while self.checkRunFile():
            current = self.run_cmd(cmd)[:-1]
            if current != prev_content and prev_content != '':
                start_index = 0
            display_content = '                ' + current + '                '
            lcd.setCursor(0,0)
            lcd.message(datetime.now().strftime('%b %d  %H:%M\n'))
            lcd.setCursor(0,1)
            lcd.message('')
            lcd.message(display_content[start_index:start_index+16])
            start_index = start_index + 1
            if start_index > len(current) + 16:
                start_index = 0
            prev_content = current
            sleep(0.5)

disp = Display()
disp.run()
